package com.meshnetics.gb.util.formatters;

import java.nio.ByteBuffer;

/**
 * Base class for number formatters, which format numbers as pair of
 * decimal and hex values. First is decimal, then second is hex
 * representaion (in brackets).
 *
 * @author Yury Aserchev (yaserchev@meshnetics.com)
 *         Date: 20.06.2008 18:33:57
 */
abstract class AbstractNumberFormatter implements NumberFormatter {
    /**
     * Returns String representation of the value as pair of decimal and
     * hex values. First is decimal, then second is hex representaion
     * (in brackets)
     * @param value source value.
     * @return result String.
     * @throws IllegalArgumentException if passed value is out of
     * appropriate range.
     */
    public String formatNumber(final long value) {
        checkRange(value);
        return new StringBuffer(String.valueOf(value)).append(" (").
                append(BufferFormatters.HEX_NUMBER.format(getBuffer(value))).
                append(")").toString();
    }

    /**
     * Returns source value converted to a bytes, which are packed into byte
     * buffer. <br/><b> Notes: </b><br/>1. All data in byte buffer is
     * interpreting as value, so byte byffer should not have any rubbish
     * bytes.<br/>2. Bytes in buffer are expected in most-significant-first
     * (BIG_ENDIAN) order.<br/>3. Byte buffer should not be readonly buffer.
     * @param value source value as long.
     * @return result byte buffer.
     */
    protected abstract ByteBuffer getBuffer(final long value);

    /**
     * Check if formatting value is in expected range. Used only for
     * "self-checking" - to avoid incorrect result when wrong value is passed
     * for conversion to String.
     * @param value source value.
     */
    protected abstract void checkRange(final long value);
}
